package com.baidu.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.baidu.captcha.CaptchaRender;
import com.baidu.captcha.Touclick;
import com.baidu.config.Constant;
import com.baidu.config.MainConfig;
import com.baidu.emus.ErrorCode;
import com.baidu.emus.UserGroup;
import com.baidu.interceptor.LoginInterceptor;
import com.baidu.model.BDUser;
import com.baidu.model.Dept;
import com.baidu.model.Invite;
import com.baidu.model.MyTB;
import com.baidu.model.Reply;
import com.baidu.model.ReplyContent;
import com.baidu.model.SysUser;
import com.baidu.util.CommonUtil;
import com.baidu.util.MD5Util;
import com.baidu.util.BaiDuApi;
import com.baidu.validator.RegisterValidator;
import com.baidu.vo.SysUserInfo;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.oreilly.servlet.Base64Encoder;

public class UserController extends Controller {
	
	public final static String secretKey = "7e6f37aa-b8e5-4b27-8e7f-de7df04f1d11";
	
	private final static int cookieMaxAge = 60 * 60 * 24;
	
	@Clear(value=LoginInterceptor.class)
	public void captcha(){
		String sessionId = this.getSession().getId();
		CaptchaRender captchaRender = new CaptchaRender();
		String captcha = captchaRender.getMd5RandonCode();
		CacheKit.put("CaptchaFilter", CaptchaRender.DEFAULT_CAPTCHA_MD5_CODE_KEY + sessionId, captcha);
		this.render(captchaRender);
	}
	
	/**
	 * 注册（跳转）
	 */
	@Clear(value=LoginInterceptor.class)
	public void reg(){
		this.setAttr("userName", "");
		this.setAttr("password", "");
		this.setAttr("email", "");
		this.setAttr("isInvite", MainConfig.custom_prop.getBoolean("isInvite"));//是否邀请注册
		this.setAttr("inviteCode", MainConfig.custom_prop.getBoolean("isInvite")?"":"");
		this.render("register.html");
	}
	
	/**
	 * 注册（保存注册信息）
	 */
	@Before(RegisterValidator.class)
	@Clear(value=LoginInterceptor.class)
	public void register(){
		String userName = this.getPara("userName");
        String password = this.getPara("password");
        String email = this.getPara("email");
        SysUser bean = new SysUser();
        String guid = UUID.randomUUID().toString();
		bean.set("guid", guid);
		bean.set("userName", userName);
		bean.set("password", MD5Util.toMd5(password + userName));
		bean.set("email",email);
		bean.set("createTime", new Date());
		bean.set("isDeleted", false);
		bean.set("group", UserGroup.normal.getCode());
		bean.save();
		//注册成功 更新邀请码的使用状态
		if(MainConfig.custom_prop.getBoolean("isInvite")){
			Invite i = Invite.dao.queryByCode(this.getPara("inviteCode"));
			i.set("isUsed", true);
			i.set("useTime", new Date());
			i.set("userGuid", guid);
			i.set("group", UserGroup.normal.getCode());
			i.update();
		}
		this.setAttr("status", ErrorCode.success.getCode());
		this.setAttr("message", "注册成功,请登陆");
		this.render("login.html");
	}
	
	/**
	 * 登陆（页面）
	 */
	@Clear(value=LoginInterceptor.class)
	public void toLogin(){
		this.render("login.html");
	}
	/**
	 * 登陆（验证）
	 * @throws UnsupportedEncodingException 
	 */
	@Clear(value=LoginInterceptor.class)
	public void login() throws UnsupportedEncodingException{
		//String sessionId = this.getSession().getId();
		String userName = getPara("userName").trim();
		String password = getPara("password").trim();
		//String captcha = getPara("captcha");
		Boolean remember = getParaToBoolean("remember");
		Boolean flag = false;
		SysUser user = SysUser.dao.findFirst("select * from sys_user where isDeleted=false and userName=? and password=?", userName, MD5Util.toMd5(password+userName));
		//String md5Code = CacheKit.get("CaptchaFilter", CaptchaRender.DEFAULT_CAPTCHA_MD5_CODE_KEY + sessionId);
		int time = 0;
		if(remember!=null && remember == true){//记住登陆，设置有效期为一年
			time = cookieMaxAge * 365;
			flag = true;
		}else{//默认记住登陆一天
			time = cookieMaxAge;
			flag = checkCaptcha();
		}
//		if(StrKit.isBlank(captcha)){
//			this.setAttr("status",ErrorCode.captchaError.getCode());
//			this.setAttr("message","请输入验证码");
//			this.render("login.html");
//		}else{
			//if(!CaptchaRender.validate(md5Code, captcha)){
		if(!flag){
			this.setAttr("status",ErrorCode.captchaError.getCode());
			this.setAttr("message","验证码错误");
			this.render("login.html");
		}else{
			if(user != null){
				SysUserInfo sysUser = new SysUserInfo(user.getStr("guid"),user.getStr("userName"),user.getStr("nickName"),user.getInt("group"));
				this.setAttr("status",ErrorCode.success.getCode());
				this.setAttr("message","登陆成功");
				long validTime = System.currentTimeMillis() + (time * 1000);
				String cookieValueWithMd5 = MD5Util.toMd5(user.getStr("userName") + ":"+
						user.getStr("password") + ":" + validTime + ":" + secretKey);
				String cookieValue = user.getStr("userName") + ":" + validTime + ":" + cookieValueWithMd5;
				String cookieValueBase64 = new String(Base64Encoder.encode(cookieValue.getBytes()).getBytes(),"utf-8");
				this.setSessionAttr("user", sysUser);
				setCookie("LOGINBUSS", URLEncoder.encode(cookieValueBase64, "utf-8"), time + cookieMaxAge);
				this.redirect(CommonUtil.getHostPath(this.getRequest()));
			}else{
				this.setAttr("status",ErrorCode.loginFailed.getCode());
				this.setAttr("message","用户名或密码错误");
				this.render("login.html");
			}
		}
//		}
	}
	
	/**
	 * 点触验证码二次验证
	 * @return
	 */
	@SuppressWarnings("unused")
	private Boolean checkCaptcha(){
		String website_key = MainConfig.custom_prop.get("website_key");
		String private_key = MainConfig.custom_prop.get("private_key");
		String check_address = this.getPara("check_address");
		String check_key = this.getPara("check_key");
		String ip = Touclick.getIpAddr(this.getRequest());
		return Touclick.check(website_key, private_key, check_key, check_address, null, null, null);
	}
	
	/**
	 * 退出
	 */
	@Clear(value=LoginInterceptor.class)
	public void logout(){
		this.removeCookie("LOGINBUSS");
		this.redirect(CommonUtil.getHostPath(getRequest()));
	}
	
	/**
	 * 显示用户列表
	 */
	public void userList(){
		Map<String, Object> map = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("from sys_user a where a.isDeleted=false");
		Page<SysUser> page = SysUser.dao.paginate(this.getParaToInt("page"), this.getParaToInt("rows"), "select a.*", sql.toString());
		//Page<SysUser> page = SysUser.dao.getUserPage(this.getParaToInt("page"), this.getParaToInt("rows"));
		map.put("total", page.getTotalRow());
		map.put("rows", page.getList());
		String jsonKit = JsonKit.toJson(map);
		//this.renderJson(map);
		this.renderText(jsonKit);
	}
	
	
	/**
	 * 部门列表
	 */
	public void deptList(){
		//Map<String, Object> map = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("from dept a where a.isDeleted=false and a.pid=0 order by a.id");
		List<Dept> list= Dept.dao.find(sql.toString());
		//Page<Dept> page = Dept.dao.paginate(this.getParaToInt("page"), this.getParaToInt("rows"), "select a.*", sql.toString());
		//Page<SysUser> page = SysUser.dao.getUserPage(this.getParaToInt("page"), this.getParaToInt("rows"));
		//map.put("total", page.getTotalRow());
		//map.put("rows", page.getList());
		//String jsonKit = JsonKit.toJson(map);
		//this.renderJson(map);
		//this.renderText(jsonKit);
		String jsonKit = JsonKit.toJson(list);
		this.renderText(jsonKit);
	}
	public void getChildren(List<Dept> list, Integer id){
		if(null != list && list.size() != 0){
			for (int i = 0; i < list.size(); i++) {
				Dept dept = list.get(i);
				dept.setChildren(Dept.dao.getDeptByPid(dept.getInt("id")));
			}
		}
	}
	
	
	/**
	 * 绑定百度账号
	 * @throws Exception 
	 */
	public void loginBaiDu () throws Exception{
		String account = this.getPara("account");
		String password = this.getPara("password");
		//获取cookie
		String bduss = new BaiDuApi().getBduss(account, password).get("bduss").toString();
		if(bduss != null){
			BDUser bd = new BDUser();
			bd.set("tbAccount", account);
			bd.set("userId", 1);//暂时写死存admin
			bd.set("cookie", bduss);
			bd.set("createTime", new Date());
			bd.set("isDeleted", false);
			bd.save();
			this.renderJson("绑定成功");
		}else {
			this.renderJson("绑定失败,需要输入验证码");
		}
	}
	
	/**
	 * 获取 我喜欢的贴吧
	 * @throws Exception 
	 */
	public void getMyLoveTieBa() throws Exception{
//		String userId = this.getPara("id");
//		List<BDUser> bd = BDUser.dao.findByUserId(userId);
		//String cookieValue = bd.getStr("bduss");
//		List<MyTB> list = new SignUtil().getMyLikedTB(cookieValue);
//		for (MyTB tb : list) {
//			MyTB.dao.saveTB(tb);
//		}
		this.renderText("success");
	}
	
	/**
	 * 我的贴吧列表
	 */
	public void tieBaList(){
		Map<String, Object> map = new HashMap<String, Object>();
		Integer userId = this.getParaToInt("id");
		StringBuffer sql = new StringBuffer();
		sql.append(" from my_tb a");
		sql.append(" left join bd_user b on a.bdId=b.id");
		sql.append(" left join sys_user c on b.userId=c.id");
		sql.append(" where a.isDeleted=false");
		sql.append(" and b.userId=?");//暂时写死
		String selectHead = "select a.*";
		Page<MyTB> page =MyTB.dao.paginate(this.getParaToInt("page"), this.getParaToInt("rows"), selectHead, sql.toString(),userId);
		map.put("total", page.getTotalRow());
		map.put("rows", page.getList());
		String jsonKit = JsonKit.toJson(map);
		this.renderText(jsonKit);
	}
	
	/**
	 * 忽略
	 */
	public void huLueSign(){
		Integer id = this.getParaToInt("id");
		Boolean flag = this.getParaToBoolean("flag");
		MyTB tb = MyTB.dao.findById(id);
		tb.set("isHuLue", flag);
		tb.update();
	}
	
	/**
	 * 签到我关注的贴吧
	 * @throws Exception 
	 */
	public void signMyLoveTieBa() throws Exception{
//		Map<String, Object> map = new HashMap<String, Object>();
//		String userId = this.getPara("guid");
//		BDUser bd = BDUser.dao.findByUserId(userId);
//		String bduss = bd.getStr("bduss");
//		List<MyTB> list = MyTB.dao.queryMyLoveTieBa(bd.getInt("id"));
//		if(null != list && list.size() > 0){
//			//循环贴吧 进行签到
//			for (MyTB tb : list) {
//				new SignUtil().signDo(tb, bduss).update();
//			}
//			map.put("status", "success");
//			map.put("message", "操作成功");
//		}else{
//			//返回签到失败，重新获取关注的贴吧
//			map.put("status", "fail");
//			map.put("message", "请先获取关注的贴吧");
//		}
//		this.renderJson(map);
	}
	
	/**
	 * 百度账号管理(跳转)
	 */
	public void baiduid(){
		String mod = getPara("mod");
		if(StrKit.notBlank(mod) && mod.equals("first")){
			//第一次进入 未绑定账号给出提示
			this.setAttr("mod","first");
		}
		this.render("baiduManage.html");
	}	
	
	/**
	 * 百度账号管理(获取数据)
	 */
	public void baiDuManage(){
		SysUserInfo sysUser = (SysUserInfo)this.getSessionAttr("user");
		List<BDUser> list = BDUser.dao.findByUserId(sysUser.getGuid());
		this.renderJson(list);
	}
	
	/**
	 * 手动绑定（bduss）
	 * @throws Exception 
	 */
	public void manual() throws Exception{
		SysUserInfo sysUser = (SysUserInfo)this.getSessionAttr("user");
		String bduss = this.getPara("bduss");
		List<BDUser> list = BDUser.dao.findByUserId(sysUser.getGuid());
		if(null != list && list.size() < 5){
			if(StrKit.notBlank(bduss)){
				//验证bduss是不是有效
				Map<String, Object> map = new BaiDuApi().getUserInfo(bduss);
				if(map != null && map.get("user_name_show") != null){
					BDUser bdUser = new BDUser();
					bdUser.set("guid", UUID.randomUUID().toString());
					bdUser.set("nickName", map.get("user_name_show").toString());
					bdUser.set("userGuid", sysUser.getGuid());
					bdUser.set("tbAccount", map.get("email").toString());
					bdUser.set("bduss", bduss);
					bdUser.set("createTime", new Date());
					bdUser.set("isDeleted", false);
					bdUser.save();
				}
			}
		}
		this.redirect(CommonUtil.getHostPath(getRequest())+"user/baiduid");
	}	
	
	/**
	 * 解绑百度账号
	 */
	public void unbundling(){
	    //删除百度账号
		BDUser user = BDUser.dao.findById(this.getPara("guid"));
		user.set("isDeleted", true);
		user.update();
		//删除百度账号相关信息
		MyTB.dao.delByBDUserId(this.getPara("guid"));
		//删除回复信息
		Reply.dao.delByBDGuid(getPara("guid"));
		//删除自定义回帖内容
		ReplyContent.dao.delByBDGuid(getPara("guid"));
		this.renderJson(CommonUtil.getReturnMsg(ErrorCode.success.getCode(), "解绑成功", null));
	}
	
	/**
	 * 自动绑定百度账号
	 * @throws Exception 
	 */
	public void auto() throws Exception{
		SysUserInfo sysUser = (SysUserInfo)this.getSessionAttr("user");
		String bdAccount = this.getPara("bdAccount");
		String password = this.getPara("password");
		//获取cookie
		String bduss = new BaiDuApi().getBduss(bdAccount, password).get("bduss").toString();
		Map<String, Object> map = new BaiDuApi().getUserInfo(bduss);
		BDUser bean = BDUser.dao.findByUserAndBduss(sysUser.getGuid(), map.get("user_name_show").toString());
		if(bduss != null && bean == null){
			BDUser bdUser = new BDUser();
			bdUser.set("guid", UUID.randomUUID().toString());
			bdUser.set("nickName", map.get("user_name_show").toString());
			bdUser.set("userGuid", sysUser.getGuid());
			bdUser.set("tbAccount", map.get("email").toString());
			bdUser.set("bduss", bduss);
			bdUser.set("createTime", new Date());
			bdUser.set("isDeleted", false);
			bdUser.save();
		}
		this.redirect(CommonUtil.getHostPath(getRequest())+"user/baiduid");
	}	
	
	/**
	 * 邀请码管理
	 */
	public void icm(){
		SysUserInfo sysUser = this.getSessionAttr("user");
		Integer  pageNumber = 1;
		if(this.getParaToInt("pageNumber") != null){
			pageNumber = this.getParaToInt("pageNumber");
		}
		StringBuffer sql = new StringBuffer();
		sql.append(" from sys_invite a");
		sql.append(" left join sys_user b on a.creator=b.guid");
		sql.append(" left join sys_user c on a.userGuid=c.guid");
		sql.append(" where a.creator=?");
		String selectHead = "select a.*,c.userName as userName";
		sql.append(" order by a.isUsed,a.createTime"); 
		Page<Invite> page = Invite.dao.paginate(pageNumber, Constant.pageSize, selectHead, sql.toString(),sysUser.getGuid());
		this.setAttr("page", page);
		this.render("invite.html"); 
	}
	
	/**
	 * 设置邀请码有效/无效
	 */
	public void valid(){
		String guid = this.getPara("guid");
		Invite i = Invite.dao.findById(guid);
		if(i.getBoolean("isValid")){
			i.set("isValid", false).update();
		}else{
			i.set("isValid", true).update();
		}
		redirect(CommonUtil.getHostPath(this.getRequest())+"user/icm");
	}
	
	/**
	 * 添加一个邀请码（只有管理员有此权限）
	 */
	public void addOneCode(){
		SysUserInfo sysUser = this.getSessionAttr("user");
		Invite i = new Invite();
		String guid = UUID.randomUUID().toString();
		i.set("guid", guid);
		i.set("code", guid.substring(22).replace("-", "").toUpperCase());
		i.set("createTime", new Date());
		i.set("isUsed", false);
		i.set("creator", sysUser.getGuid());
		i.set("isValid", 1);
		i.save();
		redirect(CommonUtil.getHostPath(this.getRequest())+"user/icm");
	}
	
	/**
	 * 用户管理列表
	 */
	public void um(){
	    Integer  pageNumber = 1;
	    if(this.getParaToInt("pageNumber") != null){
	        pageNumber = this.getParaToInt("pageNumber");
	    }
	    StringBuffer sql = new StringBuffer();
	    sql.append(" from sys_user a");
	    sql.append(" where 1=1");
	    String selectHead = "select a.*,(select count(b.guid) from bd_user b where b.isDeleted=false and a.guid=b.userGuid) as bcount";
	    sql.append(" order by a.createTime desc"); 
	    Page<SysUser> page = SysUser.dao.paginate(pageNumber, Constant.pageSize, selectHead, sql.toString());
	    this.setAttr("page", page);
	    this.setAttr("groupList", UserGroup.values());
	    this.render("user.html"); 
	}
	
	/**
	 * 禁用/解禁用户
	 */
	public void cz(){
	    String guid = this.getPara("guid");
	    SysUser u = SysUser.dao.findById(guid);
	    if(u.getBoolean("isDeleted")){
	        u.set("isDeleted", false).update();
	    }else{
	        u.set("isDeleted", true).update();
	    }
	    redirect(CommonUtil.getHostPath(this.getRequest())+"user/um");
	}
	/**
	 * 设置用户角色
	 */
	public void setGroup(){
	    String guid = this.getPara("guid");
	    Integer group = this.getParaToInt("group");
	    SysUser u = SysUser.dao.findById(guid);
	    u.set("group", group).update();
	    this.renderJson(CommonUtil.getReturnMsg(200, "设置成功", null));
	}
	
}
